package com.zhiche.lisa.bms.service.capital.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.zhiche.lisa.bms.dao.mapper.capital.CapitalArrangementMapper;
import com.zhiche.lisa.bms.dao.model.capital.CapitalArrDtl;
import com.zhiche.lisa.bms.dao.model.capital.CapitalArrangement;
import com.zhiche.lisa.bms.dao.model.fee.FeePayable;
import com.zhiche.lisa.bms.dao.model.pay.PayApply;
import com.zhiche.lisa.bms.enums.FeePayableBaseEnum;
import com.zhiche.lisa.bms.pojo.bo.capital.CapitalArrDtlAndApplyBO;
import com.zhiche.lisa.bms.pojo.dto.driver.DriverDTO;
import com.zhiche.lisa.bms.pojo.dto.fleet.FleetDTO;
import com.zhiche.lisa.bms.pojo.dto.util.CapitalArrangeDTO;
import com.zhiche.lisa.bms.pojo.dto.util.FcPayApplyDTO;
import com.zhiche.lisa.bms.pojo.vo.capital.CapitalArrDtlVO;
import com.zhiche.lisa.bms.pojo.vo.capital.CapitalArrangementAndDtl;
import com.zhiche.lisa.bms.pojo.vo.pay.PayAffirmApplyVO;
import com.zhiche.lisa.bms.pojo.vo.pay.PayAffirmDetailVO;
import com.zhiche.lisa.bms.service.capital.CapitalArrDtlService;
import com.zhiche.lisa.bms.service.capital.CapitalArrangementService;
import com.zhiche.lisa.bms.service.fee.FeePayableService;
import com.zhiche.lisa.bms.service.pay.PayAffirmService;
import com.zhiche.lisa.bms.service.pay.PayApplyService;
import com.zhiche.lisa.bms.service.price.PriceFiRateService;
import com.zhiche.lisa.bms.service.utils.LspUtil;
import com.zhiche.lisa.bms.service.utils.OtmUtil;
import com.zhiche.lisa.bms.service.utils.PayApiUtil;
import com.zhiche.lisa.bms.service.utils.common.AccountBindUtil;
import com.zhiche.lisa.bms.service.utils.common.identityCodeUtil.CodeUtil;
import com.zhiche.lisa.core.supports.BaseException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 排款计划 服务实现类
 * </p>
 *
 * @author WangShuiJin
 * @since 2018-09-29
 */
@Service
public class CapitalArrangementServiceImpl extends ServiceImpl<CapitalArrangementMapper, CapitalArrangement> implements CapitalArrangementService {
    //注入引用service
    @Autowired
    private PriceFiRateService priceFiRateService;
    @Autowired
    private LspUtil lspUtil;
    @Autowired
    private OtmUtil otmUtil;
    @Autowired
    private CapitalArrDtlService capitalArrDtlService;
    @Autowired
    private PayApplyService payApplyService;
    @Autowired
    private CodeUtil codeUtil;
    @Autowired
    private PayAffirmService payAffirmService;
    @Autowired
    private PayApiUtil payApiUtil;
    @Autowired
    private FeePayableService feePayableService;

    /*
     * 获取排款计划分页信息
     *
     * @param inParamPage
     * @return
     */
    @Override
    public Page<CapitalArrangement> selectCapitalArrangement(Page<CapitalArrangement> inParamPage) {
        try {
            EntityWrapper<CapitalArrangement> capitalArrangementEntityWrapper = bindPageEw(inParamPage.getCondition());
            capitalArrangementEntityWrapper.orderBy("gmt_create desc, id desc");
            return this.selectPage(inParamPage.setCondition(new HashMap<>()), capitalArrangementEntityWrapper);
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("获取排款计划信息错误");
        }
    }

    /**
     * 获取排款计划详明
     *
     * @param id
     * @return
     */
    @Override
    public CapitalArrangementAndDtl selectCapitalArrangementAndDetail(Long id) {
        try {
            CapitalArrangementAndDtl capitalArrangementAndDtl = new CapitalArrangementAndDtl();
            List<CapitalArrDtlAndApplyBO> capitalArrDtlAndApplyBOS = new ArrayList<>();
            CapitalArrangement capitalArrangement = this.selectById(id);
            BeanUtils.copyProperties(capitalArrangement, capitalArrangementAndDtl);
//            List<CapitalArrangementAndApplyBO> capitalArrangementDtls = capitalArrangementDtlService.selectCapitalArrangementDtlListByHeaderId(id);
            List<CapitalArrDtl> capitalArrDtls = capitalArrDtlService.selectCapitalArrDtlListByHeadId(id);
//            capitalArrangementAndDtl.setCapitalArrangementDtls(capitalArrangementDtls);
//            if (!CollectionUtils.isEmpty(capitalArrangementDtls)) {
//                List<Long> ids = new ArrayList<>();
//                capitalArrangementDtls.forEach(capitalArrangementDtl -> ids.add(capitalArrangementDtl.getPayId()));
//                capitalArrangementAndDtl.setPayApplies(payApplyService.queryPayApplyByIds(ids));
//            }
            if (!CollectionUtils.isEmpty(capitalArrDtls)) {
                List<Long> ids = new ArrayList<>();
                capitalArrDtls.forEach(capitalArrDtl -> {
                    ids.add(capitalArrDtl.getPayId());
                    CapitalArrDtlAndApplyBO capitalArrDtlAndApplyBO = new CapitalArrDtlAndApplyBO();
                    BeanUtils.copyProperties(capitalArrDtl, capitalArrDtlAndApplyBO);
                    capitalArrDtlAndApplyBOS.add(capitalArrDtlAndApplyBO);
                });
                capitalArrangementAndDtl.setPayApplies(payApplyService.queryPayApplyByIds(ids));
            }
            capitalArrangementAndDtl.setCapitalArrDtls(capitalArrDtlAndApplyBOS);
            return capitalArrangementAndDtl;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("获取排款计划信息错误");
        }
    }

    /**
     * 绑定分页查询条件
     *
     * @param condition
     * @return
     */
    private EntityWrapper<CapitalArrangement> bindPageEw(Map<String, Object> condition) {
        EntityWrapper<CapitalArrangement> capitalArrangementEntityWrapper = new EntityWrapper<>();
        if (!CollectionUtils.isEmpty(condition)) {
            capitalArrangementEntityWrapper.orderBy("gmt_create desc, id desc");
            for (Map.Entry<String, Object> entry :
                    condition.entrySet()) {
                if (Objects.nonNull(entry.getValue()) && !Strings.isNullOrEmpty(entry.getValue().toString())) {
                    if ("code".equals(entry.getKey())) {
                        capitalArrangementEntityWrapper.like("code", entry.getValue().toString());
                    }
                    if ("state".equals(entry.getKey())) {
                        capitalArrangementEntityWrapper.eq("state", entry.getValue());
                    }
                    if ("gmtCreateStart".equals(entry.getKey())) {
                        capitalArrangementEntityWrapper.ge("gmt_create", entry.getValue());
                    }
                    if ("gmtCreateEnd".equals(entry.getKey())) {
                        capitalArrangementEntityWrapper.le("gmt_create", entry.getValue());
                    }
                }
            }
        }
        return capitalArrangementEntityWrapper;
    }

    /**
     * 新增排款计划头单信息
     *
     * @param capitalArrangement
     */
    @Override
    public void insertCapitalArrangement(CapitalArrangement capitalArrangement) {
        new AccountBindUtil<CapitalArrangement>().bindCreatorAndTenantId(capitalArrangement, true);
        if (Objects.isNull(capitalArrangement.getState())) {
            capitalArrangement.setState(0);
        }
        capitalArrangement.setCode(codeUtil.getCapitalArrangementCode().getNextCode(null));
        capitalArrangement.setGmtCreate(new Date());
        this.insert(capitalArrangement);
    }

    /**
     * 新增排款计划头单以及详明信息
     *
     * @param capitalArrangementAndDtl
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertCapitalArrangementAndDtl(CapitalArrangementAndDtl capitalArrangementAndDtl) {
        try {
            CapitalArrangement capitalArrangement = new CapitalArrangement();
            BeanUtils.copyProperties(capitalArrangementAndDtl, capitalArrangement);
            //修改数量
//            capitalArrangement.setQuantity(capitalArrangementAndDtl.getCapitalArrangementDtls().size());
            capitalArrangement.setQuantity(capitalArrangementAndDtl.getCapitalArrDtls().size());
            if (Objects.isNull(capitalArrangement.getSum())) {
                throw new BaseException("请选择本次排款金额");
            }
            this.insertCapitalArrangement(capitalArrangement);

            /*
             * 遍历并调整CapitalDtl详明数据
             */
            //所有已分配详明的总共分配金额
            final BigDecimal[] dtlExecuteSum = {new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP)};
            //对应的支付单id
            List<Long> payIds = new ArrayList<>();
//            List<CapitalArrangementDtl> capitalArrangementDtls = new ArrayList<>();
//            capitalArrangementAndDtl.getCapitalArrangementDtls().forEach(capitalArrangementDtl -> {
//                payIds.add(capitalArrangementDtl.getPayId());
//
//                if (capitalArrangementDtl.getExecuteSum() == null) {
//                    capitalArrangementDtl.setExecuteSum(BigDecimal.ZERO);
//                } else {
//                    dtlExecuteSum[0] = dtlExecuteSum[0].add(capitalArrangementDtl.getExecuteSum());
//                }
//
//                if (capitalArrangementDtl.getNoExecuteSum() == null) {
//                    capitalArrangementDtl.setNoExecuteSum(BigDecimal.ZERO);
//                }
//                capitalArrangementDtl.setHeadId(capitalArrangement.getId());
//                capitalArrangementDtl.setBalance(capitalArrangementDtl.getPaymentSum().subtract(capitalArrangementDtl.getExecuteSum()));
//                capitalArrangementDtls.add(capitalArrangementDtl);
//            });
            List<CapitalArrDtl> capitalArrDtls = new ArrayList<>();
            capitalArrangementAndDtl.getCapitalArrDtls().forEach(capitalArrDtl -> {
                payIds.add(capitalArrDtl.getPayId());

                if (capitalArrDtl.getExecuteSum() == null) {
                    capitalArrDtl.setExecuteSum(BigDecimal.ZERO);
                } else {
                    dtlExecuteSum[0] = dtlExecuteSum[0].add(capitalArrDtl.getExecuteSum());
                }

                if (capitalArrDtl.getNoExecuteSum() == null) {
                    capitalArrDtl.setNoExecuteSum(BigDecimal.ZERO);
                }
                capitalArrDtl.setHeadId(capitalArrangement.getId());
                capitalArrDtl.setBalance(capitalArrDtl.getPaymentSum().subtract(capitalArrDtl.getExecuteSum()));
                capitalArrDtls.add(capitalArrDtl);
            });
            /*
             * 根据对应id，验证并调整价格
             */
            List<PayApply> oldPayApplies = payApplyService.selectBatchIds(payIds);
            List<PayApply> newPayApplies = new ArrayList<>();
//            capitalArrangementAndDtl.getCapitalArrangementDtls().forEach(
            capitalArrangementAndDtl.getCapitalArrDtls().forEach(
                    capitalArrDtl -> {
                        //获取排款详明的为排款金额和已排款金额
                        BigDecimal noExecuteSum = capitalArrDtl.getNoExecuteSum();
                        BigDecimal executeSum = capitalArrDtl.getExecuteSum();
                        Long payId = capitalArrDtl.getPayId();
                        //修找匹配数据
                        for (int i = 0; i < oldPayApplies.size(); i++) {
                            if (oldPayApplies.get(i).getId().compareTo(payId) == 0) {
                                PayApply payApplyItem = oldPayApplies.get(i);

                                //验证排款金额（此次的排款剩余和排款数量相加等于上次未排款金额）
                                if (payApplyItem.getNoExecuteSum() != null) {
                                    if (payApplyItem.getNoExecuteSum().compareTo(noExecuteSum.add(executeSum)) != 0) {
                                        throw new BaseException("支付申请单：" + payApplyItem.getPayApplyCode() + "对应排款金额不匹配");
                                    }
                                } else {
                                    payApplyItem.setNoExecuteSum(BigDecimal.ZERO);
                                }
                                if (capitalArrDtl.getThisOilExecutePaySum() != null) {
                                    if (capitalArrDtl.getThisOilExecutePaySum().compareTo(payApplyItem.getOilErPaySum()) > 0) {
                                        throw new BaseException("支付申请单：" + payApplyItem.getPayApplyCode() + "尾款余额不足");
                                    }
                                } else {
                                    capitalArrDtl.setThisOilExecutePaySum(BigDecimal.ZERO);
                                }

                                if (payApplyItem.getExecuteSum() == null) {
                                    payApplyItem.setExecuteSum(BigDecimal.ZERO);
                                }
                                payApplyItem.setNoExecuteSum(noExecuteSum);
                                payApplyItem.setExecuteSum(payApplyItem.getExecuteSum().add(executeSum));
                                payApplyItem.setCurrentExecute(executeSum);
                                payApplyItem.setOilErPaySum(payApplyItem.getOilErPaySum().subtract(capitalArrDtl.getThisOilExecutePaySum()));
                                payApplyItem.setOilAlPaySum(payApplyItem.getOilAlPaySum().add(capitalArrDtl.getThisOilExecutePaySum()));

                                BigDecimal thisCashPaySum = capitalArrDtl.getThisCashExecutePaySum();
                                payApplyItem.setCashErPaySum(payApplyItem.getCashErPaySum().subtract(thisCashPaySum));
                                payApplyItem.setCashAlPaySum(payApplyItem.getCashAlPaySum().add(thisCashPaySum));
                                newPayApplies.add(payApplyItem);
                                oldPayApplies.remove(i);


                                CapitalArrDtl bindCapitalDtlItem = capitalArrDtl;
                                BeanUtils.copyProperties(payApplyItem, bindCapitalDtlItem);
                                bindCapitalDtlItem.setOilAlPaySum(capitalArrDtl.getThisOilExecutePaySum());
                                bindCapitalDtlItem.setCashAlPaySum(thisCashPaySum);
//                                bindCapitalDtlItem.setCurrentExecute(capitalArrDtl.getCurrentExecute());

                                BeanUtils.copyProperties(bindCapitalDtlItem, capitalArrDtl);
                                break;
                            }
                        }
                    }
            );
            payApplyService.updateBatchById(newPayApplies);

            //原数据中可分配的金额于此次分配金额（此次分配的金额和剩余未分配的金额总和）不相同
//            if (oldPaysNoExecuteSum.compareTo(dtlNoExecuteSum.add(dtlExecuteSum)) != 0)
//                throw new BaseException("详明可分配金额不足，请刷新后重新绑定");

            /*
             * 绑定主表信息
             */
            //详明使用总金额是否大于总共分配的金额
            if (capitalArrangement.getSum().compareTo(dtlExecuteSum[0]) > 0) {
                //主表排款金额大于等于详明的排款金额（详明使用未超出），计算未使用的金额
                BigDecimal dtlNoExecute = capitalArrangement.getSum().subtract(dtlExecuteSum[0]);
                capitalArrangement.setNoExecuteSum(dtlNoExecute);
            } else if (capitalArrangement.getSum().compareTo(dtlExecuteSum[0]) == 0) {
                //使用金额等于分配金额，设置未分配金额为零
                capitalArrangement.setNoExecuteSum(BigDecimal.ZERO);
            } else {
                throw new BaseException("详明金额超出可分配范围");
            }
            //保存同步后的详明和主表数据
//            capitalArrangementDtlService.insertBatch(capitalArrangementDtls);
            capitalArrDtlService.insertCapitalArrDtls(capitalArrDtls);

            capitalArrangement.setExecuteSum(dtlExecuteSum[0]);
            this.updateById(capitalArrangement);
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("新增排款信息出现错误");
        }
    }

    /**
     * 审核
     *
     * @param id
     * @param token
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void capitalArrangementExamine(Long id, String token) {
        CapitalArrangement capitalArrangement = this.selectById(id);
        if (Objects.isNull(capitalArrangement)) {
            throw new BaseException("排款单不存在");
        }
        if (new Integer(1).equals(capitalArrangement.getState())) {
            throw new BaseException("该排款单已被审核，请重新选择");
        }
        capitalArrangement.setState(1);
        this.updateById(capitalArrangement);

        Map<String, Integer> existsItem = new HashMap<>();
        List<CapitalArrangeDTO> capitalArrangeDTOS = new ArrayList<>();

        List<CapitalArrDtl> capitalArrDtls = capitalArrDtlService.selectCapitalArrDtlListByHeadId(id);
        List<CapitalArrDtlVO> capitalArrDtlVOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(capitalArrDtls)) {
            throw new BaseException("该排款单无匹配明细");
        }
        capitalArrDtls.forEach(capitalArrOldDtl -> {
            CapitalArrDtlVO capitalArrDtl = new CapitalArrDtlVO();
            BeanUtils.copyProperties(capitalArrOldDtl, capitalArrDtl);
            String lspId = "";
            String lspName = "";
            if (capitalArrDtl.getExecuteSum() == null) {
                capitalArrDtl.setExecuteSum(BigDecimal.ZERO);
            }
            if (capitalArrDtl.getBillType() == null) {
                capitalArrDtl.setBillType(0L);
            }
            //寻找承运商id和名称
            if (new Long("10").compareTo(capitalArrDtl.getBillType()) == 0) {
                if (capitalArrDtl.getLspId() == null || capitalArrDtl.getLspName() == null) {
                    throw new BaseException("对应排款单无承运商信息");
                }
                lspId = String.valueOf(capitalArrDtl.getLspId());
                lspName = capitalArrDtl.getLspName();
            } else if (new Long("20").compareTo(capitalArrDtl.getBillType()) == 0) {
                FleetDTO fleetDTO = new FleetDTO();
                fleetDTO.setId(capitalArrDtl.getLspId());
                fleetDTO = lspUtil.getFleetOne(fleetDTO, token);
                if (fleetDTO == null) {
                    throw new BaseException("无匹配的车队信息");
                }
                if (fleetDTO.getLspId() == null || fleetDTO.getLspName() == null) {
                    throw new BaseException("对应车队无承运商信息");
                }
                lspId = String.valueOf(fleetDTO.getLspId());
                lspName = fleetDTO.getLspName();

                capitalArrDtl.setBindCarrierId(fleetDTO.getLspId());
                capitalArrDtl.setBindCarrierName(fleetDTO.getLspName());
                capitalArrDtl.setBindFleetId(fleetDTO.getId());
                capitalArrDtl.setBindFleetName(fleetDTO.getFleetName());
            } else if (new Long("30").compareTo(capitalArrDtl.getBillType()) == 0) {
                DriverDTO driverDTO = lspUtil.queryDriverById(String.valueOf(capitalArrDtl.getLspId()), token);
                if (driverDTO == null) {
                    throw new BaseException("无匹配的司机信息");
                }
                if (driverDTO.getLspId() == null || driverDTO.getLspName() == null) {
                    throw new BaseException("对应司机无承运商信息");
                }
                lspId = String.valueOf(driverDTO.getLspId());
                lspName = driverDTO.getLspName();

                capitalArrDtl.setBindCarrierId(driverDTO.getLspId());
                capitalArrDtl.setBindCarrierName(driverDTO.getLspName());
                capitalArrDtl.setBindFleetId(new Long(driverDTO.getFleetId() == null ? 0 : driverDTO.getFleetId()));
                capitalArrDtl.setBindDriverId(driverDTO.getId());
                capitalArrDtl.setBindDriverName(driverDTO.getName());
            } else {
                throw new BaseException("详明排款单无匹配类型");
            }
            //验证对应承运商是否已绑定
            if (existsItem.containsKey(lspId)) {
                CapitalArrangeDTO capitalArrangeDTO = capitalArrangeDTOS.get(existsItem.get(lspId));
                capitalArrangeDTO.setMoney(
                        capitalArrDtl.getExecuteSum().add(capitalArrangeDTO.getMoney())
                );
            } else {
                CapitalArrangeDTO capitalArrangeDTO = new CapitalArrangeDTO();
                capitalArrangeDTO.setShipperId(lspId);
                capitalArrangeDTO.setShipperName(lspName);
                capitalArrangeDTO.setMoney(capitalArrDtl.getExecuteSum());
//
                capitalArrangeDTOS.add(capitalArrangeDTO);
                existsItem.put(lspId, capitalArrangeDTOS.size() - 1);
            }
            capitalArrDtlVOS.add(capitalArrDtl);
        });
//        //TODO 调用otmutls.capitalToBmsService
//        capitalArrangeDTOS.forEach(capitalArrangeDTO -> {
//            if (capitalArrangeDTO.getMoney() != null) {
//                PriceFiRate priceFiRate = priceFiRateService.queryPriceFiRateById(Long.parseLong(capitalArrangeDTO.getShipperId()));
//                if (priceFiRate != null && priceFiRate.getFiRate() != null) {
//                    capitalArrangeDTO.setMoney(capitalArrangeDTO.getMoney().multiply(priceFiRate.getFiRate()));
//                }
//            }
//            System.out.println(capitalArrangeDTO);
//            BmsServiceResult bmsServiceResult = otmUtil.capitalToBmsService(capitalArrangeDTO);
//            if (bmsServiceResult.isSuccess())
//                System.out.println(bmsServiceResult);
//        });
        PayAffirmDetailVO payAffirmDetailVO = new PayAffirmDetailVO();
        payAffirmDetailVO.setPayDate(new Date());
        payAffirmDetailVO.setPayType("10");
        payAffirmDetailVO.setCapitalId(capitalArrangement.getId());
        payAffirmDetailVO.setPaySum(BigDecimal.ZERO);

        List<PayAffirmApplyVO> payAffirmApplies = new ArrayList<>();
        Map<Long, FcPayApplyDTO> capitalArrDtlIdAndFcPayApplyDTO = new HashMap<>();
        List<FcPayApplyDTO> fcPayApplyDTOS = new ArrayList<>();
        Integer notHaveCashSumSize = 0;
        Integer notHaveOilSumSize = 0;
        for (CapitalArrDtlVO capitalArrDtl : capitalArrDtlVOS) {
            BigDecimal oilAlPaySum = capitalArrDtl.getOilAlPaySum();
            BigDecimal cashAlPaySum = capitalArrDtl.getCashAlPaySum();

            PayAffirmApplyVO payAffirmApply = new PayAffirmApplyVO();
            if (oilAlPaySum == null || BigDecimal.ZERO.compareTo(oilAlPaySum) >= 0) {
                notHaveOilSumSize++;
            } else {
                FcPayApplyDTO fcPayApplyDTO = new FcPayApplyDTO();
                fcPayApplyDTO.setShipmentGid(capitalArrangement.getCode());
                fcPayApplyDTO.setPaymentSubject(capitalArrDtl.getBindCarrierName());
                fcPayApplyDTO.setFleetName(capitalArrDtl.getBindFleetName());
                fcPayApplyDTO.setPayType("2");
                fcPayApplyDTO.setProvider("万金油");
                fcPayApplyDTO.setApplyForMoney(oilAlPaySum);
                fcPayApplyDTOS.add(fcPayApplyDTO);
                capitalArrDtlIdAndFcPayApplyDTO.put(capitalArrDtl.getId(), fcPayApplyDTO);
            }
            if (cashAlPaySum == null || BigDecimal.ZERO.compareTo(cashAlPaySum) >= 0) {
                notHaveCashSumSize++;
            } else {
                payAffirmApply.setId(capitalArrDtl.getId());
                payAffirmApply.setSum(capitalArrDtl.getCashAlPaySum());
                payAffirmApply.setNotPaidSum(payAffirmApply.getSum());
                payAffirmApply.setPaidSum(payAffirmApply.getSum().subtract(payAffirmApply.getNotPaidSum()));
                if (capitalArrDtl != null && capitalArrDtl.getPayId() != null) {
                    PayApply payApply = payApplyService.selectById(capitalArrDtl.getPayId());
                    if (payApply != null) {
                        payAffirmApply.setFleetId(payApply.getLspId() != null ? Long.parseLong(payApply.getLspId()) : null);
                        payAffirmApply.setFleetName(payApply.getLspName());
                        payAffirmApply.setPayCode(payApply.getPayApplyCode());
                    }
                }
                payAffirmApplies.add(payAffirmApply);

                payAffirmDetailVO.setPaySum(payAffirmDetailVO.getPaySum().add(payAffirmApply.getSum()));
            }
        }
        if (!Objects.deepEquals(notHaveCashSumSize, capitalArrDtls.size())) {
            payAffirmDetailVO.setPayAffirmApplyVOList(payAffirmApplies);
            payAffirmService.insertPayAffirm(payAffirmDetailVO, false);
        }
        if (!Objects.deepEquals(notHaveOilSumSize, capitalArrDtls.size())) {
            List<CapitalArrDtl> updateCapitalArrDtls = new ArrayList<>();
            capitalArrDtlIdAndFcPayApplyDTO.forEach((aLong, fcPayApplyDTO) -> {
                String applyNo = payApiUtil.createPayapply(fcPayApplyDTO).getData();
                CapitalArrDtl capitalArrDtl = new CapitalArrDtl();
                capitalArrDtl.setId(aLong);
                capitalArrDtl.setCostId(applyNo);
                updateCapitalArrDtls.add(capitalArrDtl);
            });
            if (!CollectionUtils.isEmpty(updateCapitalArrDtls)) {
                capitalArrDtlService.updateBatchById(updateCapitalArrDtls);
            }
        }

        // 更新应付订单的是否排款状态
        updateFeePayableIsCapitalFlag(capitalArrangement);
    }

    /**
     * 更新应付订单的是否排款状态
     *
     * @param capitalArrangement
     */
    private void updateFeePayableIsCapitalFlag(CapitalArrangement capitalArrangement) {
        List<CapitalArrDtl> capitalArrDtlList = capitalArrDtlService.selectCapitalArrDtlListByHeadId(capitalArrangement.getId());
        if (CollectionUtils.isEmpty(capitalArrDtlList)) {
            return;
        }
        Set<Long> payIdSet = new HashSet<>();
        List<FeePayable> updateFeePayableList = Lists.newArrayList();
        capitalArrDtlList.stream().filter(dtl -> Objects.nonNull(dtl.getPayId())).forEach(dtl -> {
            if (!payIdSet.contains(dtl.getPayId())) {
                // 获取对应的支付申请单
                List<Long> payIdList = Lists.newArrayList();
                payIdList.add(dtl.getPayId());
                List<FeePayable> feePayableList = feePayableService.queryFeePayableListByPayApplyIdList(payIdList);
                // 未排款金额
                BigDecimal noExecuteSum = dtl.getNoExecuteSum();
                if (!CollectionUtils.isEmpty(feePayableList)) {
                    feePayableList.forEach(feePayable -> {
                        // 判断是否部分还是全部排款
                        if (Objects.nonNull(noExecuteSum)) {
                            if (noExecuteSum.compareTo(BigDecimal.ZERO) > 0) {
                                // 未排款金额不为0 - 部分排款
                                feePayable.setIsArrPay(FeePayableBaseEnum.PART.getCode());
                            } else {
                                // 已全部排款
                                feePayable.setIsArrPay(FeePayableBaseEnum.ALL.getCode());
                            }
                        }
                        String arrPayCode = feePayable.getArrPayCode();
                        if (StringUtils.isNotBlank(arrPayCode) && !arrPayCode.contains(capitalArrangement.getCode())) {
                            feePayable.setArrPayCode(feePayable.getArrPayCode() + "; " + capitalArrangement.getCode());
                        } else {
                            feePayable.setArrPayCode(capitalArrangement.getCode());
                        }
                        feePayable.setGmtModify(new Date());
                    });
                    updateFeePayableList.addAll(feePayableList);
                }
                payIdSet.add(dtl.getPayId());
            }
        });
        if (!CollectionUtils.isEmpty(updateFeePayableList)) {
            feePayableService.updateBatchById(updateFeePayableList);
        }

    }
}
